package com.gjt.serverSocket;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created with Intel IDEA.
 * 日志(import java.util.logging.Logger;) 是线程安全的
 * 日志的严重性级别：
 * Level.SERVER, Level.WARNING, Level.INFO, Level.CONFIG, Level.FINER, Level.FINER, Level.FINEST
 * 通常对审计日志使用info, 对错误日志使用warning或者server, 一般日志记录会有时间戳和客户端的地址
 * <p>
 * <p>
 * 记录请求和错误的daytime 服务器增加日志记录
 *
 * @Auther: gjt
 * @Date: 2024/5/9 17:17
 */
public class LoggingDaytimeServer {
    private final static int PORT = 13;
    private final static Logger auditLogger = Logger.getLogger("requests");
    private final static Logger errorLogger = Logger.getLogger("errors");

    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(50);
        try (ServerSocket server = new ServerSocket(PORT)) {

            while (true) {
                try {
                    Socket socket = server.accept();
                    Callable<Void> daytimeTask = new DaytimeTask(socket);
                    pool.submit(daytimeTask);
                } catch (IOException e) {
                    errorLogger.log(Level.SEVERE,"Accept error", e);
                } catch (RuntimeException ex){
                    errorLogger.log(Level.SEVERE,"unexpected error " + ex.getMessage(),ex);
                }
            }
        } catch (IOException e) {
            errorLogger.log(Level.SEVERE,"Couldn't start server", e);
        }catch (RuntimeException ex){
            errorLogger.log(Level.SEVERE,"Couldn't start server:"+ ex.getMessage(), ex);
        }
    }


    private static class DaytimeTask implements Callable<Void> {
        private Socket connection;

        public DaytimeTask(Socket connection) {
            this.connection = connection;
        }

        @Override
        public Void call() throws Exception {
            try {
                Date now = new Date();
                // 记录日志以防客户断开连接
                auditLogger.info(now + " " + connection.getRemoteSocketAddress());
                BufferedWriter out = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
                out.write(now + "\r\n");
                out.flush();
            } catch (IOException e) {

            } finally {
                try {
                    connection.close();
                } catch (IOException ignore) {
                }
            }
            return null;
        }
    }

}
